const express = require('express');
const router = express.Router();
const multer = require('multer');
const csv = require('csv-parser');
const fs = require('fs');
const path = require('path');
const database = require('../utils/database');
const exportUtils = require('../utils/export');

// 配置文件上传
const upload = multer({ dest: 'uploads/' });

/**
 * 管理端路由
 * 处理管理员的增删改查和导出功能
 */

// ==================== 区域管理 ====================

/**
 * 获取所有区域
 * GET /api/admin/areas
 */
router.get('/areas', async (req, res) => {
    try {
        const { search } = req.query;
        let sql = 'SELECT * FROM areas';
        let params = [];
        
        if (search) {
            sql += ' WHERE name LIKE ?';
            params.push(`%${search}%`);
        }
        
        sql += ' ORDER BY name';
        
        const areas = await database.all(sql, params);
        res.json({
            success: true,
            data: areas
        });
    } catch (error) {
        console.error('获取区域列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取区域列表失败',
            error: error.message
        });
    }
});

/**
 * 添加区域
 * POST /api/admin/areas
 */
router.post('/areas', async (req, res) => {
    try {
        const { name, description } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                message: '区域名称不能为空'
            });
        }
        
        // 检查是否已存在
        const existing = await database.get('SELECT id FROM areas WHERE name = ?', [name]);
        if (existing) {
            return res.status(400).json({
                success: false,
                message: '区域名称已存在'
            });
        }
        
        const result = await database.run(
            'INSERT INTO areas (name, description) VALUES (?, ?)',
            [name, description || '']
        );
        
        res.json({
            success: true,
            message: '区域添加成功',
            data: { id: result.id }
        });
    } catch (error) {
        console.error('添加区域失败:', error);
        res.status(500).json({
            success: false,
            message: '添加区域失败',
            error: error.message
        });
    }
});

/**
 * 更新区域
 * PUT /api/admin/areas/:id
 */
router.put('/areas/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { name, description } = req.body;
        
        if (!name) {
            return res.status(400).json({
                success: false,
                message: '区域名称不能为空'
            });
        }
        
        // 检查是否存在同名区域（排除当前区域）
        const existing = await database.get(
            'SELECT id FROM areas WHERE name = ? AND id != ?',
            [name, id]
        );
        if (existing) {
            return res.status(400).json({
                success: false,
                message: '区域名称已存在'
            });
        }
        
        await database.run(
            'UPDATE areas SET name = ?, description = ? WHERE id = ?',
            [name, description || '', id]
        );
        
        res.json({
            success: true,
            message: '区域更新成功'
        });
    } catch (error) {
        console.error('更新区域失败:', error);
        res.status(500).json({
            success: false,
            message: '更新区域失败',
            error: error.message
        });
    }
});

/**
 * 删除区域
 * DELETE /api/admin/areas/:id
 */
router.delete('/areas/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        // 检查是否有关联的维修项目
        const items = await database.get(
            'SELECT COUNT(*) as count FROM repair_items WHERE area_id = ?',
            [id]
        );
        
        if (items.count > 0) {
            return res.status(400).json({
                success: false,
                message: '该区域下还有维修项目，无法删除'
            });
        }
        
        await database.run('DELETE FROM areas WHERE id = ?', [id]);
        
        res.json({
            success: true,
            message: '区域删除成功'
        });
    } catch (error) {
        console.error('删除区域失败:', error);
        res.status(500).json({
            success: false,
            message: '删除区域失败',
            error: error.message
        });
    }
});

// ==================== 维修项目管理 ====================

/**
 * 获取维修项目列表
 * GET /api/admin/items
 */
router.get('/items', async (req, res) => {
    try {
        const { area_id, search, page = 1, limit = 50 } = req.query;
        
        let sql = `SELECT r.*, a.name as area_name 
                   FROM repair_items r 
                   LEFT JOIN areas a ON r.area_id = a.id 
                   WHERE 1=1`;
        let params = [];
        
        if (area_id) {
            sql += ' AND r.area_id = ?';
            params.push(area_id);
        }
        
        if (search) {
            sql += ' AND (r.name LIKE ? OR r.specification LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        
        sql += ' ORDER BY r.name';
        
        // 分页
        const offset = (page - 1) * limit;
        sql += ' LIMIT ? OFFSET ?';
        params.push(parseInt(limit), offset);
        
        const items = await database.all(sql, params);
        
        // 获取总数
        let countSql = 'SELECT COUNT(*) as total FROM repair_items r WHERE 1=1';
        let countParams = [];
        
        if (area_id) {
            countSql += ' AND r.area_id = ?';
            countParams.push(area_id);
        }
        
        if (search) {
            countSql += ' AND (r.name LIKE ? OR r.specification LIKE ?)';
            countParams.push(`%${search}%`, `%${search}%`);
        }
        
        const countResult = await database.get(countSql, countParams);
        
        res.json({
            success: true,
            data: {
                items,
                total: countResult.total,
                page: parseInt(page),
                limit: parseInt(limit)
            }
        });
    } catch (error) {
        console.error('获取维修项目列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取维修项目列表失败',
            error: error.message
        });
    }
});

/**
 * 添加维修项目
 * POST /api/admin/items
 */
router.post('/items', async (req, res) => {
    try {
        const { area_id, name, specification, unit, price, remarks } = req.body;
        
        if (!area_id || !name || !unit || !price) {
            return res.status(400).json({
                success: false,
                message: '请填写所有必填字段'
            });
        }
        
        const result = await database.run(
            `INSERT INTO repair_items (area_id, name, specification, unit, price, remarks) 
             VALUES (?, ?, ?, ?, ?, ?)`,
            [area_id, name, specification || '', unit, price, remarks || '']
        );
        
        res.json({
            success: true,
            message: '维修项目添加成功',
            data: { id: result.id }
        });
    } catch (error) {
        console.error('添加维修项目失败:', error);
        res.status(500).json({
            success: false,
            message: '添加维修项目失败',
            error: error.message
        });
    }
});

/**
 * 更新维修项目
 * PUT /api/admin/items/:id
 */
router.put('/items/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { area_id, name, specification, unit, price, remarks } = req.body;
        
        if (!area_id || !name || !unit || !price) {
            return res.status(400).json({
                success: false,
                message: '请填写所有必填字段'
            });
        }
        
        await database.run(
            `UPDATE repair_items 
             SET area_id = ?, name = ?, specification = ?, unit = ?, price = ?, remarks = ? 
             WHERE id = ?`,
            [area_id, name, specification || '', unit, price, remarks || '', id]
        );
        
        res.json({
            success: true,
            message: '维修项目更新成功'
        });
    } catch (error) {
        console.error('更新维修项目失败:', error);
        res.status(500).json({
            success: false,
            message: '更新维修项目失败',
            error: error.message
        });
    }
});

/**
 * 删除维修项目
 * DELETE /api/admin/items/:id
 */
router.delete('/items/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        await database.run('DELETE FROM repair_items WHERE id = ?', [id]);
        
        res.json({
            success: true,
            message: '维修项目删除成功'
        });
    } catch (error) {
        console.error('删除维修项目失败:', error);
        res.status(500).json({
            success: false,
            message: '删除维修项目失败',
            error: error.message
        });
    }
});

/**
 * 批量删除维修项目
 * POST /api/admin/items/batch-delete
 */
router.post('/items/batch-delete', async (req, res) => {
    try {
        const { ids } = req.body;
        
        if (!ids || !Array.isArray(ids) || ids.length === 0) {
            return res.status(400).json({
                success: false,
                message: '请提供要删除的项目ID列表'
            });
        }
        
        // 构建删除SQL
        const placeholders = ids.map(() => '?').join(',');
        const sql = `DELETE FROM repair_items WHERE id IN (${placeholders})`;
        
        await database.run(sql, ids);
        
        res.json({
            success: true,
            message: `成功删除 ${ids.length} 个维修项目`
        });
    } catch (error) {
        console.error('批量删除维修项目失败:', error);
        res.status(500).json({
            success: false,
            message: '批量删除维修项目失败',
            error: error.message
        });
    }
});

/**
 * 批量导入维修项目
 * POST /api/admin/items/import
 */
router.post('/items/import', upload.single('file'), async (req, res) => {
    try {
        const { area_id } = req.body;
        
        if (!area_id) {
            return res.status(400).json({
                success: false,
                message: '请选择区域'
            });
        }
        
        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: '请选择CSV文件'
            });
        }
        
        const results = [];
        const errors = [];
        
        // 读取CSV文件
        await new Promise((resolve, reject) => {
            fs.createReadStream(req.file.path)
                .pipe(csv())
                .on('data', (data) => results.push(data))
                .on('end', resolve)
                .on('error', reject);
        });
        
        let successCount = 0;
        
        // 处理每一行数据
        for (let i = 0; i < results.length; i++) {
            const row = results[i];
            try {
                // 根据CSV文件的列名映射
                const name = row['维修内容'] || row['项目名称'] || row['name'];
                const specification = row['规格型号'] || row['规格'] || row['specification'];
                const unit = row['单位'] || row['unit'];
                const price = parseFloat(row['结算单价'] || row['单价'] || row['price']);
                const remarks = row['备注'] || row['remarks'] || '';
                
                if (!name || !unit || isNaN(price)) {
                    errors.push(`第${i + 1}行数据不完整`);
                    continue;
                }
                
                await database.run(
                    `INSERT INTO repair_items (area_id, name, specification, unit, price, remarks) 
                     VALUES (?, ?, ?, ?, ?, ?)`,
                    [area_id, name, specification || '', unit, price, remarks]
                );
                
                successCount++;
            } catch (error) {
                errors.push(`第${i + 1}行导入失败: ${error.message}`);
            }
        }
        
        // 删除临时文件
        fs.unlinkSync(req.file.path);
        
        res.json({
            success: true,
            message: `导入完成，成功${successCount}条，失败${errors.length}条`,
            data: {
                successCount,
                errorCount: errors.length,
                errors: errors.slice(0, 10) // 只返回前10个错误
            }
        });
    } catch (error) {
        console.error('批量导入失败:', error);
        
        // 清理临时文件
        if (req.file && fs.existsSync(req.file.path)) {
            fs.unlinkSync(req.file.path);
        }
        
        res.status(500).json({
            success: false,
            message: '批量导入失败',
            error: error.message
        });
    }
});

// ==================== 计价单管理 ====================

/**
 * 获取计价单列表
 * GET /api/admin/quotations
 */
router.get('/quotations', async (req, res) => {
    try {
        const { area_id, start_date, end_date, search, page = 1, limit = 20 } = req.query;
        
        let sql = `SELECT q.*, a.name as area_name 
                   FROM quotations q 
                   LEFT JOIN areas a ON q.area_id = a.id 
                   WHERE 1=1`;
        let params = [];
        
        if (area_id) {
            sql += ' AND q.area_id = ?';
            params.push(area_id);
        }
        
        if (start_date) {
            sql += ' AND q.repair_date >= ?';
            params.push(start_date);
        }
        
        if (end_date) {
            sql += ' AND q.repair_date <= ?';
            params.push(end_date);
        }
        
        if (search) {
            sql += ' AND (q.location LIKE ? OR q.person LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        
        sql += ' ORDER BY q.created_at DESC';
        
        // 分页
        const offset = (page - 1) * limit;
        sql += ' LIMIT ? OFFSET ?';
        params.push(parseInt(limit), offset);
        
        const quotations = await database.all(sql, params);
        
        // 获取总数
        let countSql = 'SELECT COUNT(*) as total FROM quotations q WHERE 1=1';
        let countParams = [];
        
        if (area_id) {
            countSql += ' AND q.area_id = ?';
            countParams.push(area_id);
        }
        
        if (start_date) {
            countSql += ' AND q.repair_date >= ?';
            countParams.push(start_date);
        }
        
        if (end_date) {
            countSql += ' AND q.repair_date <= ?';
            countParams.push(end_date);
        }
        
        if (search) {
            countSql += ' AND (q.location LIKE ? OR q.person LIKE ?)';
            countParams.push(`%${search}%`, `%${search}%`);
        }
        
        const countResult = await database.get(countSql, countParams);
        
        res.json({
            success: true,
            data: {
                quotations,
                total: countResult.total,
                page: parseInt(page),
                limit: parseInt(limit)
            }
        });
    } catch (error) {
        console.error('获取计价单列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取计价单列表失败',
            error: error.message
        });
    }
});

/**
 * 导出计价单
 * POST /api/admin/quotations/export
 */
router.post('/quotations/export', async (req, res) => {
    try {
        const { area_id, start_date, end_date, search } = req.body;
        
        let sql = `SELECT q.*, a.name as area_name 
                   FROM quotations q 
                   LEFT JOIN areas a ON q.area_id = a.id 
                   WHERE 1=1`;
        let params = [];
        
        if (area_id) {
            sql += ' AND q.area_id = ?';
            params.push(area_id);
        }
        
        if (start_date) {
            sql += ' AND q.repair_date >= ?';
            params.push(start_date);
        }
        
        if (end_date) {
            sql += ' AND q.repair_date <= ?';
            params.push(end_date);
        }
        
        if (search) {
            sql += ' AND (q.location LIKE ? OR q.person LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        
        sql += ' ORDER BY q.created_at DESC';
        
        const quotations = await database.all(sql, params);
        
        if (quotations.length === 0) {
            return res.status(400).json({
                success: false,
                message: '没有符合条件的数据可导出'
            });
        }
        
        // 生成文件名
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
        const filename = `quotations_${timestamp}.xlsx`;
        
        // 导出Excel
        const filePath = await exportUtils.exportQuotationsToExcel(quotations, filename);
        
        res.json({
            success: true,
            message: '导出成功',
            data: {
                filename,
                downloadUrl: `/exports/${filename}`,
                count: quotations.length
            }
        });
    } catch (error) {
        console.error('导出计价单失败:', error);
        res.status(500).json({
            success: false,
            message: '导出计价单失败',
            error: error.message
        });
    }
});

/**
 * 删除计价单
 * DELETE /api/admin/quotations/:id
 */
router.delete('/quotations/:id', async (req, res) => {
    try {
        const { id } = req.params;
        
        await database.run('DELETE FROM quotations WHERE id = ?', [id]);
        
        res.json({
            success: true,
            message: '计价单删除成功'
        });
    } catch (error) {
        console.error('删除计价单失败:', error);
        res.status(500).json({
            success: false,
            message: '删除计价单失败',
            error: error.message
        });
    }
});

/**
 * 下载导入模板
 * GET /api/admin/template
 */
router.get('/template', async (req, res) => {
    try {
        const filePath = await exportUtils.generateImportTemplate();
        res.download(filePath, 'import_template.csv');
    } catch (error) {
        console.error('下载模板失败:', error);
        res.status(500).json({
            success: false,
            message: '下载模板失败',
            error: error.message
        });
    }
});

/**
 * 获取区域统计数据
 * GET /api/admin/area-stats
 */
router.get('/area-stats', async (req, res) => {
    try {
        // 获取每个区域的项目数量
        const itemStats = await database.all(`
            SELECT area_id, COUNT(*) as count 
            FROM repair_items 
            GROUP BY area_id
        `);
        
        // 获取每个区域的计价单数量
        const quotationStats = await database.all(`
            SELECT area_id, COUNT(*) as count 
            FROM quotations 
            GROUP BY area_id
        `);
        
        // 组织数据
        const stats = {};
        
        // 处理项目统计
        itemStats.forEach(stat => {
            if (!stats[stat.area_id]) {
                stats[stat.area_id] = {};
            }
            stats[stat.area_id].items = stat.count;
        });
        
        // 处理计价单统计
        quotationStats.forEach(stat => {
            if (!stats[stat.area_id]) {
                stats[stat.area_id] = {};
            }
            stats[stat.area_id].quotations = stat.count;
        });
        
        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取区域统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取区域统计失败',
            error: error.message
        });
    }
});

module.exports = router;